<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	 public function init()
        {
            if(isset($_POST['lang'])){
                Yii::app()->setLanguage($_POST['lang']);
                Yii::app()->getSession()->add('language', $_POST['lang']);
            }
            else{
              if(Yii::app()->getSession()->get('language') != "")
                Yii::app()->setLanguage(Yii::app()->getSession()->get('language'));
              else
                  Yii::app()->setLanguage(Lang::getdefaultLanguage());
            }
            parent::init();
        }

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{		
    // renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'  
		$this->render('index');
	}
	
	/**
	 * This is the default 'demo' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionDemo()
	{		
    // renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'  
		$this->render('demo');
	}
	
	/**
	 * This is the default 'pricing' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionPricing()
	{		
    // renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'  
		$this->render('pricing');
	}
	
		/**
	 * This is the default 'demo' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionDonate()
	{		
    // renders the view file 'protected/views/site/donate.php'
		  
		$this->render('donate');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
	  
    $session=new CHttpSession;
		$session->open();
		
  		// Se inicializa el contador de intentos de login
  		if(!isset($session['loginAttempts']))
  			$session['loginAttempts'] = 0;
		// Si la cantidad de intentos de login supera la cantidad permitida antes de bloquear la cuenta
		if($session['loginAttempts'] >= Yii::app()->params['attemptsBeforeLockUser'])
		{
			Yii::app()->user->setFlash('success',"Su cuenta de usuario fue inhabilitada por motivos de seguridad. Por favor contacte con el administrador del sistema para mas información.");
			$this->render('login',array('lockUser'=>true));
		}
		else
		{// Si todo está bien...
	  		$model=new UsersLoginForm;
	  		// collect user input data
			if(isset($_POST['UsersLoginForm']))
			{
				$model->attributes=$_POST['UsersLoginForm'];
				
		  		$model->scenario='formWithOutCapcha';//Por defecto se asume que no se muestra la imagen de seguridad capcha
		  		//Si la cantidad de intentos de login supera el limite entonces se valida el capcha
				if($session['loginAttempts'] >= Yii::app()->params['attemptsBeforeCapcha'])
					$model->scenario='formWithCapcha';
				
				$model->rijndaelKey = Yii::app()->params['rijndaelKey'];
				$model->cookieKey = Yii::app()->params['cookieKey'];
				
				// Valida los datos del usuario y redirecciona a la url indicada en la definicion del modulo
				if($model->validate())
				{
					unset($session['loginAttempts']);
					$this->redirect(Yii::app()->controller->module->params['logIn']);
				}
				else
				{
					$session['loginAttempts'] = $session['loginAttempts'] + 1;
					// Si la cantidad de intentos de login superó la cantidad de intentos permitidos, 
					// entonces se bloquea la cuenta del usuario ingresado si existe.
					if($session['loginAttempts'] == Yii::app()->params['attemptsBeforeLockUser'])
					{
						if($model = User::model()->findByAttributes(array('usr_nickname'=>$model->username)))
						{
							$model->usr_date_block = date('Y-m-d H:i:s');
							$model->usr_status = 0;
							$model->save();
							
							Yii::import('application.helpers.PHPMailer');
							$mail = new PHPMailer();
							$mail->IsHTML(true);
							$mail->Host = Yii::app()->controller->module->params['serverEmail'];
							$mail->From = Yii::app()->controller->module->params['supportEmail'];
							$mail->FromName = "Admin";
							$mail->Subject = utf8_decode('Activación de cuenta de usuario');	
							
					        $rijndael = new RijndaelHex(Yii::app()->params['rijndaelKey']);
					        // Se encripta la fecha de bloqueo y se agrega a la url de activación    
					        $cryptDate = $rijndael->linencrypthex($model->usr_date_block);
							$url = "http://{$_SERVER['HTTP_HOST']}/index.php?r=users/login/activate&c={$cryptDate}";
					        
					        $mail->Body = "Para activar de nuevo la cuenta de usuario debe hacer clic <a href='{$url}'>aquí</a>
										   o pegar en el navegador la siguiente url: {$url}";	
							
							$mail->AddAddress($model->usr_email);	
							$mail->Send();	
						}
						
					}
				}
			}
			else
			{
		  		$cookieNameUser = Yii::app()->params['cookieKey']."-qfdr4uc";
				//Si la cookie existe entonces se desencriptan los datos de usuario y contraseña y se muestran en el formulario.
				if(isset($_COOKIE[$cookieNameUser]))
				{
					$cookieNamePass = Yii::app()->params['cookieKey']."-qpdr3w";
					$rijndael = new RijndaelHex(Yii::app()->params['rijndaelKey']);
					$model->username = $rijndael->lindecrypthexComplex($_COOKIE[$cookieNameUser]);
			        $model->password = $rijndael->lindecrypthexComplex($_COOKIE[$cookieNamePass]);
			        $model->rememberMe = true;
				}
			}
			//Si la cantidad de intentos de login supera el limite entonces se muestra el capcha
			if($session['loginAttempts'] >= Yii::app()->params['attemptsBeforeCapcha'])
				$allowEmpty = false;
			else
				$allowEmpty = true;
			
			$this->render('login',array('model'=>$model, 'allowEmpty'=>$allowEmpty, 'lockUser'=>false));
		}
	
	}
	
	


	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	
	public function actionSingup()
	{
		  $model=new SingUpForm;
  		if(isset($_POST['SingUpForm']))
  		{
  		
        $model->attributes=$_POST['SingUpForm'];
  			if($model->validate())
  			{
  			   Yii::import('application.modules.users.helpers.RijndaelHex');
           
  			   $usuario= new User;
  			   $usuario->scenario='create';
	         $usuario->attributes=$_POST['User'];
    	         
    			$usuario->usr_nickname = $_POST['SingUpForm']['nickname'];
    			$usuario->usr_name = $_POST['SingUpForm']['name'];
    		  $usuario->usr_email = $_POST['SingUpForm']['email'];
    		  $usuario->usr_spam = $_POST['SingUpForm']['spam'];
    		  $usuario->usr_password = $_POST['SingUpForm']['password'];
    			$usuario->usr_status = 1;
    			$usuario->usr_profile = User::ROLE_EDITOR;
          $rijndael = new RijndaelHex(Yii::app()->params['rijndaelKey']);
			    $usuario->usr_password = $rijndael->linencrypthexComplex($usuario->usr_password,$usuario->usr_nickname);
		      if(!$usuario->save()){
            $model->addError('nickname','El nombre de usuario ya exsite.');        
            $model->addError('email','EL email yah a sido usado.');
          }else{
            //envio el e-mail
            $content=$this->renderFile('protected/views/site/elements/email.php', array('model' => $model), TRUE);
            $this->senEmail($content,'registre@cmsmobi.co','CMS.MOBI','SingUP');
            $this->refresh();
          }
				
        }
		  }
  	 
     $this->render('singup',array('model'=>$model));    
	}
	
	
	private function senEmail($msg,$from,$fromName,$subject)
	{
      Yii::import('application.extensions.phpmailer.JPhpMailer');
      $mail = new JPhpMailer;
      $mail->IsSMTP();
      $mail->Host = 'smpt.163.com';
      /*$mail->SMTPAuth = false;
      $mail->Username = 'yourname@163.com';
      $mail->Password = 'yourpassword';*/
      $mail->SetFrom($from, $fromName);
      $mail->Subject = $subject;
      $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
      $mail->MsgHTML($msg);
      $mail->AddAddress('john.doe@otherdomain.com', 'John Doe');
      $mail->Send();
  }
  
   /*
       * ProcesUrl method used for resolving languages if dont have get language
       * System gets default language defined from database
       */
      public static function processUrl(){

              if(isset($_POST['lang'])){
                  return Lang::findByCode(Yii::app()->language,  Yii::app()->controller->route);
              }else{ 
                  return Lang::findByCode(Lang::getdefaultLanguage(),  Yii::app()->controller->route);   
              }
      }

       /*
       * Aftereach action processUrl
       */
       protected function beforeAction($action) {
          self::processUrl();
          return parent::beforeAction($action);
      }

	
}